package com.dms.wuziqi.websocketconfig;

import lombok.extern.java.Log;
import org.apache.logging.log4j.message.Message;
import org.springframework.web.socket.*;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class WebSocketHandler extends TextWebSocketHandler {
    private static final Set<WebSocketSession> sessions=new HashSet<>();
    public static String count;

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {

        sessions.add(session);
        String count= String.valueOf(sessions.size());
        session.sendMessage(new TextMessage("欢迎链接,当前连接数:"+sessions.size()));
        session.sendMessage(new TextMessage(count));
        count= String.valueOf(sessions.size());
    }


    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        System.out.println(message.getPayload());
    }
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus status) throws Exception {
        sessions.remove(session);
    }
    public static void broadcast(String message){

        for (WebSocketSession session:sessions){
            if (session.isOpen()){
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (Exception e) {
                    System.out.println("错误");
                }
            }
        }
    }
}
